package com.pkk.penguin.frame.know.java.Javacoreknowledge.thread.lock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;

/**
 * @description: Semaphore信号量[类似于ReentrantLock]
 * @author: peikunkun
 * @create: 2019-12-27 17:41
 **/
public class SemaphoreLock extends Thread {

  /**
   * 最大支持5个线程并发
   */
  public static Semaphore semaphore = new Semaphore(5);

  /**
   * If this thread was constructed using a separate
   * <code>Runnable</code> run object, then that
   * <code>Runnable</code> object's <code>run</code> method is called;
   * otherwise, this method does nothing and returns.
   * <p>
   * Subclasses of <code>Thread</code> should override this method.
   *
   * @see #start()
   * @see #stop()
   * @see #Thread(ThreadGroup, Runnable, String)
   */
  @Override
  public void run() {
    try {
      semaphore.acquire();
      System.out.println(Thread.currentThread().getName() + "is Runnning");
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      semaphore.release();
      System.out.println(Thread.currentThread().getName() + "is Close");
    }
  }

  @Test
  public void Administrator_45_20191227174651() {
    System.out.println("欢迎使用单元测试方法【Administrator_45()_20191227174651】");
    System.out.println("此方法测试描述：【】");
    for (int i = 0; i < 10; i++) {
      final Thread thread = new Thread(new SemaphoreLock(), "SemaphoreLock-Thread" + i);
      thread.start();
      if (i == 6) {
        thread.interrupt();
      }
    }
  }


  @Test
  public void Administrator_44_20191227174639() {
    System.out.println("欢迎使用单元测试方法【Administrator_44()_20191227174639】");
    System.out.println("此方法测试描述：【】");
    for (int i = 0; i < 10; i++) {
      new Thread(new SemaphoreLock(), "SemaphoreLock-Thread").start();
    }
  }

  public static AtomicLong atomicLong=new AtomicLong(0);

  @Test
  public void Administrator_71_20191227175511() {
    System.out.println("欢迎使用单元测试方法【Administrator_71()_20191227175511】");
    System.out.println("此方法测试描述：【】");
    for (int i = 0; i < 100; i++) {
      final long l = atomicLong.addAndGet(1);
      System.out.println(l);
    }
  }


}
